<template>
  <div class="execution">
    <basic-container>
      <avue-crud ref="crud"
                 :page="page"
                 :data="tableData"
                 :table-loading="tableLoading"
                 :option="tableOption"
                 v-model="form"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @row-update="handleUpdate"
                 @row-save="handleSave"
                 @row-del="rowDel">
        <template slot="menuLeft">
          <el-button type="primary"
                     @click="handleAdd"
                     size="small">新 增
          </el-button>
          <br/><br/>
        </template>
        <template slot-scope="scope"
                  slot="menu">
          <el-button type="text"
                     icon="el-icon-check"
                     size="small"
                     plain
                     @click="handleEdit(scope.row,scope.index)">编辑
          </el-button>
          <el-button type="text"
                     icon="el-icon-delete"
                     size="small"
                     plain
                     @click="handleDel(scope.row,scope.index)">删除
          </el-button>
        </template>
        <template slot="positionIdForm"
                  slot-scope="scope">
          <avue-crud-select v-model="form.positionId"
                            placeholder="请选择广告位置"
                            :dic="adPositionList"
                            :props="adPositionProps"></avue-crud-select>
        </template>
        <template slot="valForm"
                  slot-scope="scope" v-if="form.adType ==1">
            <avue-crud-select  v-model="form.val"
                              placeholder="请选择服务类型"
                              :dic="typeOptions"
                              :props="typeProps"></avue-crud-select>

        </template>
        <template slot="adImageForm"
                  slot-scope="scope">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :limit="1"
            :file-list="fileList"
            list-type="picture-card"
            :on-success="handleUploadSuccess"
            :on-remove="handleImageRemove">
            <i class="el-icon-plus"></i>
          </el-upload>
        </template>
      </avue-crud>
    </basic-container>


    <el-dialog
      title="关联用户"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <el-table :data="couponList" max-height="300" stripe border>
        <el-table-column label="优惠券" prop="name" align="center"></el-table-column>
        <el-table-column label="所属店铺" prop="shopName" align="center"></el-table-column>
        <el-table-column align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="relatedCoupon(scope.row)">关联</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="couponList" style="margin-top: 20px;text-align: right">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleClose">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {addObj, delObj, fetchList, getObj, putObj} from '@/api/ad/advertisement'
  import {getAdPositionList} from '@/api/ad/adposition'
  import {handleImgUrl} from '@/utils/util'
  import {tableOption} from '@/const/crud/ad/advertisement'
  import {getAllTypes} from '@/api/merchantservices/merservicestype'
  import {getAllCoupon} from '@/api/marketing/coupon'

  export default {
    name: 'advertisement',
    data() {
      return {
        headers: {
          'token': Vue.cookie.get('token')
        },
        tableData: [],
        adPositionList: [],
        adPositionProps: {
          label: "positionBrief",
          value: 'id'
        },
        typeProps: {
          label: "name",
          value: 'id'
        },
        typeOptions: [],
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20 // 每页显示多少条
        },
        tableLoading: false,
        tableOption: tableOption,
        form: {
          adImage: ''
        },
        fileList: [],
        actionUrl: '',
        dialogVisible: false,
        couponList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        coupon: ''
      }
    },
    created() {
    },
    watch: {
      adType() {
        this.form.val = ''
      }
    },
    mounted: function () {
      this.actionUrl = this.$http.adornUploadUrl()
      this.getList(this.page)
    },
    computed: {
      // ...mapGetters(['permissions'])
    },
    methods: {
      getList(page, params) {
        this.tableLoading = true
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize
        }, params)).then(response => {
          this.tableData = response.data.data.records
          this.page.total = response.data.data.total
          this.tableLoading = false
          this.getAdPositionList()
        })
      },
      getAdPositionList() {
        getAdPositionList()
          .then(res => {
            this.adPositionList = res.data.data
          })
      },
      getAllTypes() {
        getAllTypes()
          .then((res) => {
            this.typeOptions = res.data.data
          })
      },
      getCouponList() {
        this.tableLoading = true
        getAllCoupon(Object.assign({
          current: this.pageIndex,
          size: this.pageSize
        })).then(response => {
          this.couponList = response.data.data.records
          this.totalPage = response.data.data.total
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd: function () {
        this.form.adImage = ''
        this.fileList = []
        this.getAdPositionList()
        this.getAllTypes()
        this.$refs.crud.rowAdd()
      },
      handleEdit(row, index) {
        this.fileList = []
        this.form.adImage = row.adImage
        if (row.adImage) {
          handleImgUrl(row.adImage).then((res) => {
            this.fileList = [{
              url: res.data
            }]
          })
        }
        this.getAdPositionList()
        this.getAllTypes()
        this.$refs.crud.rowEdit(row, index)
      },
      handleDel(row, index) {
        this.$refs.crud.rowDel(row, index)
      },
      rowDel: function (row, index) {
        var _this = this
        this.$confirm('是否确认删除ID为' + row.id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delObj(row.id)
        }).then(data => {
          _this.tableData.splice(index, 1)
          _this.$message({
            showClose: true,
            message: '删除成功',
            type: 'success'
          })
          this.getList(this.page)
        }).catch(function (err) {
        })
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate: function (row, index, done, loading) {
        putObj(row).then(data => {
          loading()
          this.tableData.splice(index, 1, Object.assign({}, row))
          this.$message({
            showClose: true,
            message: '修改成功',
            type: 'success'
          })
          done()
          this.getList(this.page)
        })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave: function (row, done, loading) {
        addObj(row).then(data => {
          loading()
          if (data.data.code === 0) {
            this.tableData.push(Object.assign({}, row))
            this.$message({
              showClose: true,
              message: '添加成功',
              type: 'success'
            })
            done()
            this.getList(this.page)
          } else {
            this.$message.error(data.data.msg)
          }
        })
      },
      /**
       * 刷新回调
       */
      refreshChange() {
        this.getList(this.page)
      },
      handleUploadSuccess(res, file) {
        this.form.adImage = res.data.bucketName + "-" + res.data.fileName;
      },
      handleImageRemove() {
        this.form.adImage = ''
      },
      handleClose() {
        this.dialogVisible = false
        this.coupon = ''
      },
      // 弹窗每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getCouponList()
      },
      // 弹窗当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getCouponList()
      },
      relatedCoupon(row) {
        this.dialogVisible = false
        this.form.val = row.id
        this.coupon = row.name
      },

      currentChange(val) {
        this.page.currentPage = val
        this.getList(this.page)
      },
      sizeChange(val) {
        this.page.currentPage = 1
        this.page.pageSize = val
        this.getList(this.page)
      }
    }
  }
</script>

<style lang="scss" scoped>

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px !important;
    color: #8c939d !important;
    width: 178px !important;
    height: 178px !important;
    line-height: 178px !important;
    text-align: center !important;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
